﻿niggles.Register({
    Instance: null,
    MenuOptions: new Array(),
    Initialise: function (niggles) {
        var me = this;
        var menu = niggles._snippets.menu;
        menu.Execute = function () { me.Execute(niggles, $(menu)) };
        menu.SetWhereAmI = function (whereIAm) { me.SetWhereAmI(whereIAm); };
        me.MenuOptions.push({ Text: 'Admin', Key: '/admin' });
        me.MenuOptions.push({ Text: 'New . . .', Key: '/new' });
    },
    Execute: function (niggles, menuSnippet) {
        this.Instance = $(menuSnippet.html());
        this.SetMenuOptions(niggles, this.Instance);
        $('#menu').append(this.Instance);
    },
    SetWhereAmI: function (whereIAm) {
        var hereAmI = $(this.Instance.find('.menu-bar-here')[0]);
        hereAmI.children().remove();
        var first = true;
        $(whereIAm).each(function () {
            if (!first) hereAmI.append($('<li>&gt;</li>'));
            hereAmI.append($('<li>' + this + '</li>'));
            first = false;
        });
    },
    SetMenuOptions: function (niggles, control) {
        var menuBarThere = $(control.find('.menu-bar-there')[0]);
        menuBarThere.html('');
        var me = this;
        $(this.MenuOptions).each(function () {
            me._addThereOption(niggles, menuBarThere, this);
        });
    },
    PostExecute: function (niggles, control) {
        control.remove();
    },
    _spawn: function (niggles, menuBarOptionSnippet) {
        return $(menuBarOptionSnippet.html());
    },
    _spawnDivider: function (niggles, menuBarDividerSnippet) {
        return $(menuBarDividerSnippet.html());
    },
    _addThereOption: function (niggles, menuBarThere, menuOption) {
        var menuBarOptionSnippet = $(niggles._snippets.menuBarOption);
        var menuBarDividerSnippet = $(niggles._snippets.menuBarDivider);

        var divider = this._spawn(niggles, menuBarDividerSnippet);
        menuBarThere.append(divider);

        var option = this._spawn(niggles, menuBarOptionSnippet);
        option.text(menuOption.Text);
        option.hover(function () { $(this).addClass('menu-bar-option-hover'); }, function () { $(this).removeClass('menu-bar-option-hover') });
        option.click(function () { niggles._controller.NavTo(menuOption.Key); });
        menuBarThere.append(option);
    }
});